package com.xy.frame.controller;

import java.util.Enumeration;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Maps;
import com.xy.commons.PageUtil;
import com.xy.frame.model.AjaxJson;
import com.xy.frame.service.RoleService;

/**
 * @author Administrator
 * 角色管理控制器
 */
@Controller
@RequestMapping("/role")
public class RoleController {

	Logger logger = LoggerFactory.getLogger(RoleController.class);
    @Autowired
    RoleService roleService;
      
    /**
     * @param currentPage
     * @param pageSize
     * @return
     * 查询角色列表数据
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public AjaxJson list(HttpServletRequest request,@RequestParam(value = "currentPage",defaultValue = "1") int currentPage,@RequestParam(value = "pageSize",defaultValue = "10") int pageSize){
        AjaxJson j = new AjaxJson();
        String roleName= request.getParameter("roleName");
        Map<String,Object> params = Maps.newHashMap();
        if(!StringUtils.isEmpty(roleName)){
        	params.put("roleName", roleName);
        }
        params.put("start",(currentPage -1)*pageSize);// > start
        params.put("end",currentPage*pageSize);  // <=  end
        Map<String,Object> pageList =  roleService.queryRoleListByPage(params);
        pageList.put(PageUtil.CURRENT,currentPage);
        pageList.put(PageUtil.PAGESIZE,pageSize);
        Integer t  = Integer.valueOf(pageList.get(PageUtil.TOTALS).toString());
        pageList.put(PageUtil.TOTALPAGE,PageUtil.getTotalPage(t,pageSize));
        j.setObj(pageList);
        if (logger.isDebugEnabled()) {
            logger.debug("请求【/role/list】处理,响应对象【"+j+"】");
        }
        return j;
    }
    /**
     * @param model
     * @return 权限页面
     */
    @RequestMapping(value = "/toPermissionPage", method = RequestMethod.GET)
    public String toPermissionPage(@RequestParam("roleNum")String roleNum, Model model,HttpServletRequest request){
        if (logger.isDebugEnabled()) {
            logger.debug("请求【/metro/role/toPermissionPage】处理页面【/view/metro/role/rolePermission.jsp】");
        }
        String jsonStr = roleService.queryAuthMenuTree(roleNum);
        model.addAttribute("userNodes",jsonStr);
        model.addAttribute("roleNum",roleNum);
        return "metro/role/rolePermission";
    }
    /**
     * @param type
     * @param model
     * @return
     * 查看、增加、修改角色页面
     */
    @RequestMapping(value = "/toRolePage", method = RequestMethod.GET)
    public String toRolePage(@RequestParam("type") String type,Model model,HttpServletRequest request){
    	
        if (logger.isDebugEnabled()) {
            logger.debug("请求【/metro/role/rolePage】处理页面【/view/metro/role/rolePage.jsp】");
        }
        model.addAttribute("type",type);//查看-0，增加 -1，修改-2
        if("2".equals(type)){
        	String roleNum = request.getParameter("roleNum");
        	model.addAttribute("roleNum",roleNum);
        }
        return "metro/role/rolePage";
    }
    /**
     * @param roleNum
     * @return
     * 获取一个角色详细信息
     */
    @RequestMapping(value = "/getRole", method = RequestMethod.GET)
    @ResponseBody
    public AjaxJson getRole(@RequestParam("roleNum") String roleNum){
        AjaxJson j = new AjaxJson();       
        Map<String,Object> roleMap = roleService.getRole(roleNum);
        j.setObj(roleMap);
        if (logger.isDebugEnabled()) {
            logger.debug("请求【/metro/role/getRole】处理,响应对象【"+j+"】");
        }
        return j;
    }

    /**
     * @return
     * 增加一个角色
     */
    @RequestMapping(value = "/addRole", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson addrole(HttpServletRequest request){
        AjaxJson j = new AjaxJson();
        Enumeration<?>  keys = request.getParameterNames();
        Map<String,Object> map = Maps.newHashMap();
        while(keys.hasMoreElements()){
        	String reqCode = keys.nextElement().toString();
        	map.put(reqCode,request.getParameter(reqCode));
        }
        try {
			roleService.addRoleOrUpdate(map);
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("系統忙，新增或更新角色【"+map.get("roleNum")+"】失败!");
			logger.error("新增或者更新角色【"+map.get("roleNum")+"】失败!",e);
		}
        if (logger.isDebugEnabled()) {
            logger.debug("请求【/metro/role/addRole】处理,响应对象【"+j+"】");
        }
        return j;
    }
    
    /**
     * @return
     * 更新权限
     */
    @RequestMapping(value = "/savePermission", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson savePermission(HttpServletRequest request,@RequestParam("roleNum") String roleNum,@RequestParam("menuNums") String menuNums){
        AjaxJson j = new AjaxJson();
         Map<String,Object> params = Maps.newHashMap();
         params.put("roleNum", roleNum);
         params.put("menuNums", menuNums.split(","));
         params.put("authLevel", 2);
        try {
			roleService.savePermission(params);
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("系統忙，保存角色【"+roleNum+"】权限失败!");
			logger.error("系統忙，保存角色【"+roleNum+"】权限失败!!",e);
		}
        if (logger.isDebugEnabled()) {
            logger.debug("请求【/metro/role/addRole】处理,响应对象【"+j+"】");
        }
        return j;
    }

    /**
     * @return
     * 删除一个角色
     * @throws Exception 
     */
    @RequestMapping(value = "/delRole", method = RequestMethod.GET)
    @ResponseBody
    public AjaxJson delRole(@RequestParam("roleNum") String roleNum) {
        AjaxJson j = new AjaxJson();
        try {
			roleService.deleteRole(roleNum);
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("系統忙，删除角色【"+roleNum+"】失败!");
			logger.error("删除角色【"+roleNum+"】失败!",e);
		}
        if (logger.isDebugEnabled()) {
            logger.debug("请求【/metro/role/delRole】处理,响应对象【"+j+"】");
        }
        return j;
    }
}